package org.linlinjava.litemall.admin.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.admin.service.AdminCarBrandService;
import org.linlinjava.litemall.admin.service.AdminCarModelService;
import org.linlinjava.litemall.admin.service.AdminCarSeriesService;
import org.linlinjava.litemall.admin.service.AdminHerbService;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.linlinjava.litemall.db.domain.LitemallCarBrand;
import org.linlinjava.litemall.db.domain.LitemallHerb;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

import static org.linlinjava.litemall.admin.util.AdminResponseCode.HERB_CODE_EXIST;
import static org.linlinjava.litemall.admin.util.AdminResponseCode.HERB_NAME_EXIST;

@RestController
@RequestMapping("/admin/herb")
@Validated
public class AdminHerbController {
    private final Log logger = LogFactory.getLog(AdminGoodsController.class);


    @Autowired
    private AdminHerbService adminHerbService;

    @Autowired
    private AdminCarBrandService carBrandService;

    @Autowired
    private AdminCarModelService carModelService;

    @Autowired
    private AdminCarSeriesService carSeriesService;

    /**
     * 查询商品
     *
     * @param herbId
     * @param code
     * @param herbName
     * @param measurement_unit
     * @param sort
     * @param order
     * @return
     */
    @RequiresPermissions("admin:herb:list")
    @RequiresPermissionsDesc(menu = {"药材品类管理", "药材品类管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(String herbId,String code,
                       String herbName,
                        String measurement_unit,String sort,
                       String order, boolean selectAll,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit
                       ) {
        List<LitemallCarBrand> list = carBrandService.list();
        return ResponseUtil.ok(list);
    }




    /**
     * 编辑商品
     *
     * @param herbExample
     * @return
     */
    @RequiresPermissions("admin:herb:update")
    @RequiresPermissionsDesc(menu = {"药材品类管理", "药材品类管理"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody LitemallHerb herbExample) {

        if (adminHerbService.checkCodeExist(herbExample.getId().toString(),herbExample.getCode())) {
            return ResponseUtil.fail(HERB_CODE_EXIST, "药材编号已存在");
        }

        Subject currentUser = SecurityUtils.getSubject();
        LitemallAdmin admin = (LitemallAdmin) currentUser.getPrincipal();
        herbExample.setUserId(admin.getId());
        adminHerbService.updateById(herbExample);
        return ResponseUtil.ok(herbExample);
    }

    /**
     * 删除商品
     *
     * @param herbExample
     * @return
     */
    @RequiresPermissions("admin:herb:delete")
    @RequiresPermissionsDesc(menu = {"药材品类管理", "药材品类管理"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody LitemallHerb herbExample) {
        adminHerbService.delete(herbExample);
        return ResponseUtil.ok(herbExample);
    }
    /**
     * 批量删除
     *
     * @param herbExampleList
     * @return
     */
    @RequiresPermissions("admin:herb:batchDelete")
    @RequiresPermissionsDesc(menu = {"药材品类管理", "药材品类管理"}, button = "批量删除")
    @PostMapping("/batchDelete")
    public Object batchDelete(@RequestBody List<LitemallHerb> herbExampleList) {
        for (LitemallHerb herbExample:herbExampleList) {
            adminHerbService.delete(herbExample);
        }
        return ResponseUtil.ok(herbExampleList);
    }

    /**
     * 批量添加
     *
     * @param herbExampleList
     * @return
     */
    @RequiresPermissions("admin:herb:batchPublish")
    @RequiresPermissionsDesc(menu = {"药材品类管理", "药材品类管理"}, button = "批量添加")
    @PostMapping("/batchPublish")
    public Object batchPublish(@RequestBody List<LitemallHerb> herbExampleList) {

        List<String> stringList = herbExampleList.stream().map(LitemallHerb::getCode)
                .collect(Collectors.toList());
        long count = stringList.stream().distinct().count();
        if (stringList.size() != count) {
            return ResponseUtil.fail(HERB_CODE_EXIST, "导入文件药材编号重复");
        }
        int i = 2;
        for (LitemallHerb herbExample:herbExampleList) {
            Subject currentUser = SecurityUtils.getSubject();
            LitemallAdmin admin = (LitemallAdmin) currentUser.getPrincipal();

            if (adminHerbService.checkCodeExist(null,herbExample.getCode())) {
                return ResponseUtil.fail(HERB_CODE_EXIST, "第"+i+"药材编号已存在");
            }
            herbExample.setUserId(admin.getId());
            herbExample.setAddTime(LocalDateTime.now());
            herbExample.setDeleted(false);
            i++;
        }

        adminHerbService.batchInsert(herbExampleList);
        return ResponseUtil.ok("success");
    }


    /**
     * 验证表单
     * @param herbExample
     * @return
     */
    private Object validate(LitemallHerb herbExample) {
        String herbName = herbExample.getHerbName();
        if (!StringUtils.isEmpty(herbName)) {
            return null;
        }
        String code = herbExample.getCode();
        if (StringUtils.isEmpty(code)) {
            return null;
        }
        String measurementUnit = herbExample.getMeasurementUnit();
        if (StringUtils.isEmpty(measurementUnit)) {
            return null;
        }
        return ResponseUtil.badArgument();
    }

    /**
     * 新增
     *
     * @param herbExample
     * @return
     */
    @RequiresPermissions("admin:herb:create")
    @RequiresPermissionsDesc(menu = {"药材品类管理", "药材品类管理"}, button = "新增")
    @PostMapping("/create")
    public Object create(@RequestBody LitemallHerb herbExample) {
        Object error = validate(herbExample);
        if (error != null) {
            return error;
        }
        if (adminHerbService.checkCodeExist(null,herbExample.getCode())) {
            return ResponseUtil.fail(HERB_CODE_EXIST, "药材编号已存在");
        }
        Subject currentUser = SecurityUtils.getSubject();
        LitemallAdmin admin = (LitemallAdmin) currentUser.getPrincipal();
        herbExample.setUserId(admin.getId());

        adminHerbService.add(herbExample);

        return ResponseUtil.ok(herbExample);
    }
}
